/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.support;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.PriorityOrdered;
import org.springframework.lang.Nullable;

/**
 * Delegate for AbstractApplicationContext's post-processor handling.
 *
 * @author Juergen Hoeller
 * @since 4.0
 */
//后置处理器注册委托类
class PostProcessorRegistrationDelegate {

     //目标：
	 // 这里我们做两个简称：BF后置=BeanFactoryPostProcessor接口，BD后置=BeanDefinitionRegistryPostProcessor接口
	 // 其中 BD后置 extends BF后置，这个可以通过查看BD接口的源码得到验证！所以调用顺序如下
	 //1、查找顺序：参数传进来的 - Factory中的BD后置 - Factory中的BF后置
	// 2、在调BD后置的时候，由于BD继承了BF，所以先调BD中子接口方法，后调继承的BF方法
	// 3、无论factory中的BD还是BF，都有可能实现PriorityOrdered或者Ordered接口
	 // 那么优先级将是这样的：PriorityOrdered - Ordered - 没实现的
	 //
	 // 下面逐步debug来验证上述的执行顺序！
	//
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

		Set<String> processedBeans = new HashSet<>();
		// 为true:
		// beanFactory为DefaultListableBeanFactory,
		// 而DefaultListableBeanFactory实现了BeanDefinitionRegistry接口，因此这边为true
		//通过查看接口的实现类，可以验证！
		if (beanFactory instanceof BeanDefinitionRegistry) {
			//进入
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//定义俩临时变量集合，一个存放BF后置处理器，一个存放BD后置处理器
			// 临时变量，用于存放BeanFactoryPostProcessor（工厂）
			List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<>();
			// 临时变量，用于存放BeanDefinitionRegistryPostProcessor
			// （实际上BD接口继承了上面的BF接口，可以通过源码验证）
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new LinkedList<>();


			// 2.首先处理入参中传进来的beanFactoryPostProcessors
			// 这些Processer是直接add到Context的属性上的，这里为空，不管他
			// 参考 AbstractApplicationContext.beanFactoryPostProcessors 属性
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					// 2.1 如果是BeanDefinitionRegistryPostProcessor的实现类，调子接口方法
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					// 2.1.1 先执行它实现的 postProcessBeanDefinitionRegistry方法（BD接口里定义，BF里没有）
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					// 2.1.2 然后添加到registryProcessors临时变量(用于最后执行BF的postProcessBeanFactory方法)
					registryProcessors.add(registryProcessor);
				} else {
					// 2.2 否则，只是普通的BeanFactoryPostProcessor
					// 2.2.1 那就直接添加到regularPostProcessors临时变量去(用于最后执行postProcessBeanFactory方法)

					regularPostProcessors.add(postProcessor);
				}
			}

			// 3.调用所有实现PriorityOrdered接口的BD后置实现类
			// 临时变量用于保存找到的的BeanDefinitionRegistryPostProcessor
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
			// 3.1 先找出所有实现了BD后置接口的Bean的beanName
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

			// 3.2 遍历这些bean
			for (String ppName : postProcessorNames) {
				// 3.3 过滤实现了PriorityOrdered接口的，其他的不要
				// PriorityOrdered接口是空的，继承了Ordered接口，Ordered里有个getOrder方法标识了顺序
				// 这个接口的意义在于，可以允许你定义带优先级的BD后置处理器，spring会按你的顺序执行
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {  // ===>  PriorityOrdered接口方法

					//3.3 放到临时变量里去，只放实现了PriorityOrdered接口的
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 3.4 将要被执行的bean name加入processedBeans，避免后续重复执行
					processedBeans.add(ppName);
				}
			}
			// 3.6 进行排序(根据getOrder方法的返回值，从小到大排序。注意看控制台，看执行后current里的顺序)
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 3.7 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
			registryProcessors.addAll(currentRegistryProcessors);
			// 3.8 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
			// 注意这货已经排过序，所以会按照排好的次序执行，这就实现了自定义后置的有序执行！！！
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 3.9 执行完毕后, 清空currentRegistryProcessors
			currentRegistryProcessors.clear();


			// 4.上面是实现了PriorityOrdered的，这步是Ordered接口的（过程跟上面的步骤3基本一样）
			// 4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的
			// 可能会有变动, 因此重新查一遍
			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// 校验是否还未执行过！关键点：上一步已经执行过的name放入了processedBeans
				// 所以这一步不会发生重复执行行为，要知道，PriorityOrdered继承了Ordered，必须排重
				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			//	一个德行，先执行完postProcessBeanDefinitionRegistry方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			// 5.最后, 调用所有剩下的BD，这些都没实现排序接口

			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				// 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类
				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
				for (String ppName : postProcessorNames) {

					// 5.2 跳过已经执行过的
					if (!processedBeans.contains(ppName)) {
						currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
						processedBeans.add(ppName);
						// 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor,
						// 因此这边将reiterate赋值为true, 代表需要再循环查找一次

						reiterate = true;
					}
				}
				sortPostProcessors(currentRegistryProcessors, beanFactory);
				registryProcessors.addAll(currentRegistryProcessors);
				// 还是一个德行，先把子接口BD里的执行完
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
			}
			// 6.调用所有BD后置处理器里的postProcessBeanFactory方法，其实这个方法是它从BF后置接口继承过来的
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			// 7.最后, 调用BF后置处理器的postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		} else {
			// Invoke factory processors registered with the context instance.
			//在上下文中注册的BF后置处理器
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!


		// 到这里 , 参数传进来的和容器中的所有BD后置处理器已经全部处理完毕,
		// 下面开始处理容器中的所有BF后置处理器
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		//还是处理三类，从前到后。PriorityOrdered - Ordered - 普通的
		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		List<String> orderedPostProcessorNames = new ArrayList<>();
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
		for (String ppName : postProcessorNames) {
			if (processedBeans.contains(ppName)) {
				// skip - already processed in first phase above
			} else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessorNames.add(ppName);
			} else {
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : orderedPostProcessorNames) {
			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

		// Finally, invoke all other BeanFactoryPostProcessors.
		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}


//目标：找出所有实现BeanPostProcessor接口的类
//	核心：和前面的一样，3步；最终目的都是实现bean后置处理器的注册
// 第一步： implement PriorityOrdered
// 第二步： implement Ordered.
// 第三步： Register all internal BeanPostProcessors
// 注意！本方法并没有去执行你定义的process方法，只是梳理并注册到factory的一个arrayList里
// 可以仔细查看控制台，直到方法结束，都没有被执行和打印
// 真正执行的时候，到很久以后了。finishBeanFactoryInitialization 这一步初始化bean前后.
	public static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
		// 1.找出所有直接实现BeanPostProcessor接口的类
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
		//加一个Processor数量检查器，就是数量不对的话打个info信息
		//beanFactory.getBeanPostProcessorCount()：系统注册到工厂里的
		//postProcessorNames.length ：我们自己实现BeanPostProcessor接口的类
		// 那么上面两项加起来不就是总数吗？  +1 又是个什么鬼？？？
		// 因为，下面new并add的这个checker本身也是个Processor！要把它也算上，数量才对
		int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
		// 2.添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中
		beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

		// 3. Separate between BeanPostProcessors that implement PriorityOrdered,
		// Ordered, and the rest.
		// 定义不同的变量用于区分，其实目的还是为了让你能控制处理器的执行顺序和优先级
		// 实现PriorityOrdered接口的BeanPostProcessor、
		// 实现Ordered接口的BeanPostProcessor、
		// 普通BeanPostProcessor


		// 3.1 继承自PriorityOrdered接口的
		List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
		// 3.2 internalPostProcessors: 用于存放Spring内部的BeanPostProcessor
		List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
		// 3.3 orderedPostProcessorNames: 用于存放实现Ordered接口的
		List<String> orderedPostProcessorNames = new ArrayList<>();
		// 3.4 nonOrderedPostProcessorNames: 用于存放普通的beanName
		List<String> nonOrderedPostProcessorNames = new ArrayList<>();


		// 4.遍历postProcessorNames, 将BeanPostProcessors按3.1 - 3.4定义的变量区分开
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				//PriorityOrdered的
				BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
				priorityOrderedPostProcessors.add(pp);
				if (pp instanceof MergedBeanDefinitionPostProcessor) {
					//实现了merged接口的，放在internal
					internalPostProcessors.add(pp);
				}
			} else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
				//Ordered 的
				orderedPostProcessorNames.add(ppName);
			} else {
				// 没实现排序接口的
				nonOrderedPostProcessorNames.add(ppName);
			}
		}

		//5.  统计分类并加载到AbstractBeanFactory的beanPostProcessors列表里去
		// 这是一个ArrayList变量，所以，会保持你放进去时候的顺序
		// 注意！这时候并没有触发processor里的方法调用。只是把它整理到了list里去（注册）
		// 5.1 排序，整理PriorityOrdered的
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // ===> 啥也没干，只是add到BF里去


		// Next, register the BeanPostProcessors that implement Ordered
		// 5.2 ordered的.
		List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
		for (String ppName : orderedPostProcessorNames) {
			// 4.1 如果ppName对应的Bean实例实现了PriorityOrdered接口,
			// 则拿到ppName对应的Bean实例并添加到priorityOrderedPostProcessors
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			orderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				// 4.2 如果ppName对应的Bean实例也实现了MergedBeanDefinitionPostProcessor接口,
				// 则将ppName对应的Bean实例添加到internalPostProcessors
				internalPostProcessors.add(pp);
			}
		}
		sortPostProcessors(orderedPostProcessors, beanFactory);
		registerBeanPostProcessors(beanFactory, orderedPostProcessors);

		// Now, register all regular BeanPostProcessors
		// 5.3 没有实现排序接口的.
		List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
		for (String ppName : nonOrderedPostProcessorNames) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			nonOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
		sortPostProcessors(internalPostProcessors, beanFactory);

		//5.4  最后，internal接口的（优先级最低）
		registerBeanPostProcessors(beanFactory, internalPostProcessors);
		// 没执行？？？对了！这里不会执行，往下看
		// Re-register post-processor for detecting inner beans as ApplicationListeners,
		// moving it to the end of the processor chain (for picking up proxies etc).
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
	}

	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		Collections.sort(postProcessors, comparatorToUse);
	}

	/**
	 * Invoke the given BeanDefinitionRegistryPostProcessor beans.
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

	/**
	 * Invoke the given BeanFactoryPostProcessor beans.
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanFactory(beanFactory);
		}
	}

	/**
	 * Register the given BeanPostProcessor beans.
	 */
	private static void registerBeanPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanPostProcessor> postProcessors) {

		for (BeanPostProcessor postProcessor : postProcessors) {
			beanFactory.addBeanPostProcessor(postProcessor);
		}
	}


	/**
	 * BeanPostProcessor that logs an info message when a bean is created during
	 * BeanPostProcessor instantiation, i.e. when a bean is not eligible for
	 * getting processed by all BeanPostProcessors.
	 */
	private static class BeanPostProcessorChecker implements BeanPostProcessor {

		private static final Log logger = LogFactory.getLog(BeanPostProcessorChecker.class);

		private final ConfigurableListableBeanFactory beanFactory;

		private final int beanPostProcessorTargetCount;

		public BeanPostProcessorChecker(ConfigurableListableBeanFactory beanFactory, int beanPostProcessorTargetCount) {
			this.beanFactory = beanFactory;
			this.beanPostProcessorTargetCount = beanPostProcessorTargetCount;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			return bean;
		}

		@Override
		public Object postProcessAfterInitialization(Object bean, String beanName) {
			if (!(bean instanceof BeanPostProcessor) && !isInfrastructureBean(beanName) &&
					this.beanFactory.getBeanPostProcessorCount() < this.beanPostProcessorTargetCount) {
				if (logger.isInfoEnabled()) {
					logger.info("Bean '" + beanName + "' of type [" + bean.getClass().getName() +
							"] is not eligible for getting processed by all BeanPostProcessors " +
							"(for example: not eligible for auto-proxying)");
				}
			}
			return bean;
		}

		private boolean isInfrastructureBean(@Nullable String beanName) {
			if (beanName != null && this.beanFactory.containsBeanDefinition(beanName)) {
				BeanDefinition bd = this.beanFactory.getBeanDefinition(beanName);
				return (bd.getRole() == RootBeanDefinition.ROLE_INFRASTRUCTURE);
			}
			return false;
		}
	}

}
